import { initGlobalState, MicroAppStateActions } from 'qiankun'

let stateVal = {}

// 初始化 state
const actions: MicroAppStateActions = initGlobalState(stateVal)

class state {
  state: any
  constructor() {
    this.state = stateVal
  }
  setState(val: object, calback: Function = () => {}) {
    this.state = Object.assign(this.state, val)
    stateVal = this.state
    // 调用方法改变数据
    //如果传来calback,则需要调改变后的方法
    calback &&
      actions.onGlobalStateChange((state, prev) => {
        calback(state, prev)
      })

    // 改变参数向子应用传递改变的值
    actions.setGlobalState(val)
  }
}

export default new state()
